﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q7.BevTree
{
    public class BevNodeSequence : BevNode
    {
        private int _currentNodeIndex = -1;

        public BevNodeSequence(string debugName)
            : base(debugName)
        {
        }

        protected override bool DoEvaluate(BevNodeInputParam input)
        {
            var index = _currentNodeIndex;
            if (index == -1)
                index = 0;

            if (CheckIndex(index))
            {
                if (Children[index].Evaluate(input))
                    return true;
            }

            return false;
        }

        protected override int DoTick(BevNodeInputParam input, BevNodeOutputParam output)
        {
            int isFinish = BRS_FINISH;

            if (_currentNodeIndex == -1)
                _currentNodeIndex = 0;

            isFinish = Children[_currentNodeIndex].Tick(input, output);
            if (isFinish == 1)
            {
                ++_currentNodeIndex;
                if (_currentNodeIndex == Children.Count)
                    _currentNodeIndex = -1;
                else
                    isFinish = BRS_EXECUTING;
            }

            if (isFinish < 0) // error

                _currentNodeIndex = -1;

            return isFinish;
        }

        protected override void DoTransition(BevNodeInputParam input)
        {
            if (CheckIndex(_currentNodeIndex))
                Children[_currentNodeIndex].Transition(input);
            _currentNodeIndex = -1;
        }
    }
}
